package com.hello.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.hello.config.ItemConfig;
import com.hello.dao.Sdao;
import com.hello.domain.City;
import com.hello.domain.User;
import com.hello.service.UserService;
import com.hello.utils.MD5;
import com.hello.utils.MailUtils;
import com.hello.validator.UserValidator;

@Controller
@RequestMapping("/userRegistration.html")
@SessionAttributes("user")
public class UserController {
	
	private UserService userService;
	private UserValidator userValidator;
	private MailUtils mailUtils;
	private Sdao dao;
	
	@Autowired
	public void setUserValidator(UserValidator userValidator) {
		this.userValidator = userValidator;
	}
	
	public UserValidator getUserValidator() {
		return this.userValidator;
	}
	
	@Autowired
	public void setDao(Sdao dao) {
		this.dao = dao;
	}
	
	public Sdao getDao() {
		return this.dao;
	}
	
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@Autowired
	public void setMailUtils(MailUtils mailUtils) {
		this.mailUtils = mailUtils;
	}
	
	@ModelAttribute("cityList")
	public List<City> populateCityList() {
		return userService.getAllCities();
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public String showUserForm(ModelMap model) {
		User user = new User();
		model.addAttribute(user);
		return "userForm";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(@ModelAttribute("user") User user, BindingResult result) throws Exception {
		userValidator.validate(user, result);
		if(result.hasErrors()) {
			return "userForm";
		} else {
			MD5 md5 = new MD5();
			md5.update(user.getPassword());
			String hexString = md5.asHex();
			user.setPassword(hexString);
			System.out.println(user.getPassword());
			if(this.getDao().insert(user) != 0)
				userService.add(user);
			else
				throw new Exception();
			boolean activationEnabled = ItemConfig.getBooleanProperty("user.account.activation.enabled");
			if(activationEnabled) {
				String[] to = new String[] { "lamusicoscos@live.cn", "lamusicoscos@sina.com", "904690742@qq.com" };
				mailUtils.sendTextMessage("lamusicoscos@gmail.com", to, null, null, null, hexString);
			}
			return "redirect:userSuccess.html";
		}
	}
}
